package com.ebt.m.customer.ui;

import android.app.DatePickerDialog;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.commons.widgets.BaseRxFragment;
import com.ebt.m.customer.CustomerUtil;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.entity.CustomerAddress;
import com.ebt.m.customer.entity.CustomerContact;
import com.ebt.m.customer.entity.CustomerDetail;
import com.ebt.m.customer.net.json.CustomerDetailJson;
import com.ebt.m.customer.util.PinyinUtil;
import com.ebt.m.customer.view.CustomerInfoUnitEditText;
import com.ebt.m.customer.view.CustomerInfoUnitEditText4Address;
import com.ebt.m.customer.view.CustomerInfoUnitTextView;
import com.ebt.m.customer.view.CustomerInfoUnitTextView4Age;
import com.ebt.m.customer.view.CustomerInfoUnitTextView4Birthday;
import com.ebt.m.customer.view.CustomerInfoUnitWrapper;
import com.ebt.m.customer.view.NumberPickerDialog;
import com.ebt.m.customer.view.VariedRadioButton;
import com.ebt.m.data.entity.ACustomerInfoItemContent;
import com.ebt.m.data.entity.Customer;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.proposal_v2.helper.PickerHelper;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.DataValidation;
import com.ebt.m.utils.DateUtils;
import com.ebt.m.utils.EbtMediaSannerClient;
import com.ebt.m.utils.EbtUtils;
import com.ebt.m.utils.PhotoCaptureUtil;
import com.ebt.m.utils.TimeUtils;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.widget.MDEBTDialog;
import com.tendcloud.tenddata.TCAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


public class FragmentCustomerDetail extends BaseRxFragment implements OnClickListener, NumberPickerDialog.SelectedListener {

    private static final String COMMA = ",";
    private static final int RADIO_BUTTON_INDEX_MALE = 0;
    private static final int RADIO_BUTTON_INDEX_FEMALE = 1;
    private static final int RADIO_BUTTON_INDEX_MARRIED_NOT = 0;
    private static final int RADIO_BUTTON_INDEX_MARRIED = 1;

    private static final int TAG_CAREER_CATEGORY = 0;
    private static final int TAG_EDUCATION_GRADING = 1;
    private static final int TAG_AGE = 2;
    private static final int TAG_LEVEL = 3;

    private View mContentView;
    private ImageView mAvatarView;//头像

    private CustomerInfoUnitEditText mNameView;//姓名
    private CustomerInfoUnitEditText mPhoneView;//电话
    private CustomerInfoUnitEditText mEmailView;//邮箱
    private CustomerInfoUnitEditText4Address mAddressView;//地址
    private CustomerInfoUnitEditText mCreditcardView;//身份证
    private CustomerInfoUnitTextView4Age mAgeView;//年龄
    private CustomerInfoUnitTextView4Birthday mBirthdayView;//生日
    private CustomerInfoUnitTextView mDegreeView;//学历
    private CustomerInfoUnitTextView mLevelView;//等级
    private CustomerInfoUnitTextView mCareerView;//等级

    //values
    private Bundle mGetBundle;
    private String mCustomerMode = CustomerConstant.CUSTOMER_DETAIL_MODE_ADD;
    private String mCustomerUuid;
    private Context mContext;
    private CustomerDetail mCustomerDetail;
    private Integer mIsConfirmed = 0;

    private CustomerInfoUnitWrapper mSexWrapperView;
    private VariedRadioButton mSexRadios;
    private CustomerInfoUnitWrapper mMarriageWrappeView;
    private VariedRadioButton mMarriageRadios;

    private String mNewPortraitPath;
    private String mOldPortraitPath;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initArgs();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = initViews(inflater, container);
        return mContentView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initValues();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    private void initArgs() {
        mGetBundle = getArguments();
        if (mGetBundle != null) {
            mCustomerMode = mGetBundle.getString(CustomerConstant.CUSTOMER_DETAIL_MODE);
            mCustomerUuid = mGetBundle.getString(CustomerConstant.CUSTOMER_UUID);
        }
    }

    public View initViews(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_customer_detail, null);
        mAvatarView = (ImageView) view.findViewById(R.id.fragment_customer_detail_iv_avatar);
        mNameView = (CustomerInfoUnitEditText) view.findViewById(R.id.fragment_customer_detail_info_unit_name);
        mPhoneView = (CustomerInfoUnitEditText) view.findViewById(R.id.fragment_customer_detail_info_unit_phone);
        mEmailView = (CustomerInfoUnitEditText) view.findViewById(R.id.fragment_customer_detail_info_unit_email);
        mAddressView = (CustomerInfoUnitEditText4Address) view.findViewById(R.id.fragment_customer_detail_info_unit_address);
        mCreditcardView = (CustomerInfoUnitEditText) view.findViewById(R.id.fragment_customer_detail_info_unit_creditcard);
        mAgeView = (CustomerInfoUnitTextView4Age) view.findViewById(R.id.fragment_customer_detail_info_unit_age);
        mBirthdayView = (CustomerInfoUnitTextView4Birthday) view.findViewById(R.id.fragment_customer_detail_info_unit_birthday);
        mDegreeView = (CustomerInfoUnitTextView) view.findViewById(R.id.fragment_customer_detail_info_unit_degree);
        mLevelView = (CustomerInfoUnitTextView) view.findViewById(R.id.fragment_customer_detail_info_unit_level);
        mCareerView = (CustomerInfoUnitTextView) view.findViewById(R.id.fragment_customer_detail_info_unit_career);

        mPhoneView.getEditText().setInputType(InputType.TYPE_CLASS_PHONE);
        mEmailView.getEditText().setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);

        mSexRadios = (VariedRadioButton) view.findViewById(R.id.customer_varied_radio_button_sex);
        mMarriageRadios = (VariedRadioButton) view.findViewById(R.id.customer_varied_radio_button_marriage);

        mBirthdayView.setTextViewContentOnClickListener(this, null);
        mAgeView.setTextViewContentOnClickListener(this, null);

        mLevelView.setTextViewContentOnClickListener(this, TAG_LEVEL);
        mCareerView.setTextViewContentOnClickListener(this, TAG_CAREER_CATEGORY);
        mDegreeView.setTextViewContentOnClickListener(this, TAG_EDUCATION_GRADING);

        mAvatarView.setOnClickListener(this);
        mSexWrapperView = (CustomerInfoUnitWrapper) view.findViewById(R.id.fragment_customer_detail_info_unit_sex);
        mSexRadios = (VariedRadioButton) view.findViewById(R.id.customer_varied_radio_button_sex);
        addViewToCustomizedView(mSexWrapperView.getContainer(), mSexRadios, null);

        mMarriageWrappeView = (CustomerInfoUnitWrapper) view.findViewById(R.id.fragment_customer_detail_info_unit_marriage);
        mMarriageRadios = (VariedRadioButton) view.findViewById(R.id.customer_varied_radio_button_marriage);
        addViewToCustomizedView(mMarriageWrappeView.getContainer(), mMarriageRadios, null);
        return view;
    }

    private void addViewToCustomizedView(ViewGroup container, View child, LayoutParams params) {
        if (child.getParent() != null) {
            ((ViewGroup) child.getParent()).removeView(child);
        }
        if (params == null) {
            container.addView(child);
        } else {
            container.addView(child, params);
        }
    }

    public void initValues() {
        mContext = this.getActivity();
        if (CustomerConstant.CUSTOMER_DETAIL_MODE_ADD.equals(mCustomerMode)) {
            initAddMode();
        } else if (CustomerConstant.CUSTOMER_DETAIL_MODE_EDIT.equals(mCustomerMode)) {
            EBTAPI ebtapi = AppInitService.getEbtApi();
            ebtapi.getCustomerDetail(mCustomerUuid).compose(RxUtil.rxTransformer(this)).subscribe(getCustomerDetailSubscriber());
        }
    }

    private void initAddMode() {
        mBirthdayView.setTextViewTextContent(DateUtils.getBirthday(null));
        mBirthdayView.setIsConfirmedUI(false);
    }

    private Observer<CustomerDetailJson> getCustomerDetailSubscriber() {
        return new Observer<CustomerDetailJson>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                UIHelper.makeToast(getContext(), getString(R.string.network_fail));
            }

            @Override
            public void onNext(CustomerDetailJson customerDetailJson) {

                if (customerDetailJson == null) {
                    showToast("客户不存在");
                    return;
                }
                if (customerDetailJson.error != null) {
                    UIHelper.makeToast(getContext(), getString(R.string.network_fail));
                    return;
                }
                if (customerDetailJson.error == null) {
                    if (customerDetailJson.data == null) {
                        UIHelper.makeToast(getContext(), getString(R.string.network_fail));
                        return;
                    } else {
                        updateOtherViews(customerDetailJson.data);
                    }
                }
            }
        };
    }

    //输入表情前的光标位置
    private int cursorPos;
    //输入表情前EditText中的文本
    private String inputAfterText;
    //是否重置了EditText的内容
    private boolean resetText;

    private void updateOtherViews(CustomerDetail customerDetail) {

        mCustomerDetail = customerDetail;
        if (mCustomerDetail != null) {
            mIsConfirmed = mCustomerDetail.getIsConfirm();
            CustomerUtil.setAvatarByUrlAndSex(getContext(), mAvatarView, mCustomerDetail.getPortraitPath(), mCustomerDetail.getSex());
            mOldPortraitPath = mNewPortraitPath = mCustomerDetail.getPortraitPath();

            if (mCustomerDetail != null) {
                //姓名
                mNameView.setEditTextText(mCustomerDetail.getName());
                //电话
                mPhoneView.setEditTextText(getCustomerContact(mCustomerDetail, CustomerConstant.CustomerContact.TYPE_PHONE));
                //邮箱
                mEmailView.setEditTextText(getCustomerContact(mCustomerDetail, CustomerConstant.CustomerContact.TYPE_EMAIL));
                //地址
                mAddressView.setEditTextText(getCustomerAddress(mCustomerDetail));
                mCreditcardView.setEditTextText(getCustomerCreditcard(mCustomerDetail));
                //年龄
                mAgeView.setTextViewTextContent(getCustomerAge(mCustomerDetail));
                //生日
                mBirthdayView.setTextViewTextContent(getCustomerBirthday(mCustomerDetail));

                if (mCustomerDetail.getIsConfirm() != null && mCustomerDetail.getIsConfirm() == 1) {
                    mBirthdayView.setIsConfirmedUI(true);
                } else {
                    mBirthdayView.setIsConfirmedUI(false);
                }
                //学历
                mDegreeView.setTextViewTextContent(getCustomerDetailEdu(mCustomerDetail));
                //等级
                mLevelView.setTextViewTextContent(getCustomerDetailLevel(mCustomerDetail));
                //职业类别
                mCareerView.setTextViewTextContent(getCustomerDetailCareerCategory(mCustomerDetail));

                //性别
                if (mCustomerDetail.getSex() == null || mCustomerDetail.getSex() == 0) {//man
                    mSexRadios.setSelectedIndex(RADIO_BUTTON_INDEX_FEMALE);
                } else {
                    mSexRadios.setSelectedIndex(RADIO_BUTTON_INDEX_MALE);
                }
                if (mCustomerDetail.getMarriage() != null && mCustomerDetail.getMarriage() != 0) {
                    mMarriageRadios.setSelectedIndex(RADIO_BUTTON_INDEX_MARRIED);
                } else {
                    mMarriageRadios.setSelectedIndex(RADIO_BUTTON_INDEX_MARRIED_NOT);
                }
            }
        }


        mNameView.setTextWatcher(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    cursorPos = mNameView.getEditText().getSelectionEnd();
                    // 这里用s.toString()而不直接用s是因为如果用s，
                    // 那么，inputAfterText和s在内存中指向的是同一个地址，s改变了，
                    // inputAfterText也就改变了，那么表情过滤就失败了
                    inputAfterText = s.toString();
                }

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    if (count >= 2) {//表情符号的字符长度最小为2
                        CharSequence input = s.subSequence(cursorPos, cursorPos + count);
                        if (containsEmoji(input.toString())) {
                            resetText = true;
                            Toast.makeText(mContext, "不支持输入Emoji表情符号", Toast.LENGTH_SHORT).show();
                            //是表情符号就将文本还原为输入表情符号之前的内容
                            mNameView.getEditText().setText(inputAfterText);
                            CharSequence text = mNameView.getEditText().getText();
                            if (text instanceof Spannable) {
                                Spannable spanText = (Spannable) text;
                                Selection.setSelection(spanText, text.length());
                            }
                        }
                    }
                } else {
                    resetText = false;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) ||
                (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000)
                && (codePoint <= 0x10FFFF));
    }

    private void showToast(String message) {
        Toast.makeText(getContext().getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }


    private String getCustomerContact(CustomerDetail customerDetail, int type) {
        List<CustomerContact> list = customerDetail.getListCustomerContact();
        List<CustomerContact> listRet = new ArrayList<>();

        if (list != null) {
            for (CustomerContact item : list) {
                if (item.ctype != null && type == item.ctype) {
                    listRet.add(item);
                }
            }
        }

        //返回第一个
        if (listRet.size() > 0) {
            return listRet.get(0).cvalue;
        }
        return "";
    }

    private String getCustomerAddress(CustomerDetail customerDetail) {
        List<CustomerAddress> list = customerDetail.getListCustomerAddress();

        if (list != null && list.size() > 0) {
            return list.get(0).details;
        }
        return "";
    }

    /**
     * 获取身份证
     *
     * @param customerDetail
     * @return
     */
    private String getCustomerCreditcard(CustomerDetail customerDetail) {
        return customerDetail.getIdCard();
    }

    //暂时没有考虑 多个号码/多个邮箱 的问题
    private void setCustomerContact(CustomerDetail customerDetail, int type, String value) {
        List<CustomerContact> list = customerDetail.getListCustomerContact();
        List<CustomerContact> listRet = new ArrayList<>();
        String uuid = null;

        if (list != null) {
            for (CustomerContact item : list) {
                if (item.ctype != null) {
                    if (type != item.ctype) {
                        listRet.add(item);
                    } else {
                        if (TextUtils.isEmpty(uuid)) {
                            uuid = item.uuid;
                        }
                    }
                }
            }
        }
        CustomerContact newItem = new CustomerContact();
        newItem.cvalue = value;
        newItem.ctype = type;
        newItem.uuid = uuid;
        if (mCustomerDetail != null) {
            newItem.customerId = mCustomerDetail.getCustomerId();
        }
        listRet.add(newItem);
        customerDetail.setListCustomerContact(listRet);
    }

    private void setCustomerAddress(CustomerDetail customerDetail, String value) {
        List<CustomerAddress> list = customerDetail.getListCustomerAddress();

        String uuid = null;
        if (list == null) {
            list = new ArrayList<>();
        } else {
            if (list.size() > 0) {
                uuid = list.get(0).uuid;
            }
        }
        list.clear();
        CustomerAddress ca = new CustomerAddress();
        ca.details = value;
        ca.uuid = uuid;
        ca.customerId = mCustomerUuid;
        list.add(ca);
        customerDetail.setListCustomerAddress(list);
    }

    private Date getDateBySecond(CustomerDetail customerDetail) {
        if (customerDetail == null || customerDetail.getBirthday() == null) {
            return DateUtils.getDefaultBirthdayDate();
        }
        return DateUtils.parseTimestampInSecondToDate(customerDetail.getBirthday());
    }

    private String getCustomerAge(CustomerDetail customerDetail) {
        return String.valueOf(DateUtils.getAge(getDateBySecond(customerDetail)));
    }

    private String getCustomerBirthday(CustomerDetail customerDetail) {
        return DateUtils.getBirthday(getDateBySecond(customerDetail));
    }

    private String getCustomerDetailEdu(CustomerDetail customerDetail) {
        if (customerDetail == null) {
            return "";
        }
        Integer i = customerDetail.getEducationGrading();
        if (i == null) {
            return "";
        }
        return CustomerConstant.EducationGrade.getShowText(i);
    }

    private String getCustomerDetailLevel(CustomerDetail customerDetail) {
        if (customerDetail == null) {
            return "";
        }

        String level = customerDetail.getLevel();
        if (level == null) {
            return "";
        }
        return level;
    }

    private String getCustomerDetailCareerCategory(CustomerDetail customerDetail) {
        if (customerDetail == null) {
            return "";
        }

        Integer i = customerDetail.getCareerCategory();
        if (i == null) {
            return "";
        }
        return CustomerConstant.CareerCategory.getShowText(i);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_customer_detail_iv_avatar:
                toSelectPhoto(mAvatarView);
                break;
            case R.id.customer_info_unit_textview_content:
                Integer iTag = (Integer) v.getTag();
                if (iTag == null) {
                    return;
                }
                int defaultValue = 0;
                switch (iTag) {
                    case TAG_CAREER_CATEGORY:
                        String career = mCareerView.getTextViewTextContent();
                        defaultValue = CustomerConstant.CareerCategory.getCareerInt(career);
                        showNumberPickerDialog(TAG_CAREER_CATEGORY, defaultValue);
                        break;
                    case TAG_EDUCATION_GRADING:
                        String edu = mDegreeView.getTextViewTextContent();
                        defaultValue = CustomerConstant.EducationGrade.getEduInt(edu);
                        showNumberPickerDialog(TAG_EDUCATION_GRADING, defaultValue);
                        break;
                    case TAG_LEVEL:
                        String level = mLevelView.getTextViewTextContent();
                        if (!TextUtils.isEmpty(level)) {
                            defaultValue = level.charAt(0) - 'A';
                        }
                        showNumberPickerDialog(TAG_LEVEL, defaultValue);
                        break;
                }
                break;
            case R.id.birthday_ll:
                showBirthdayPicker();
                break;
            case R.id.age_rl:
                String age = mAgeView.getTextViewTextContent();
                if (TextUtils.isEmpty(age.trim())) {
                    age = "30";
                }
                if (age.trim().charAt(0) >= 48 && age.trim().charAt(0) <= 57) {
                } else {
                    String birthday = mBirthdayView.getTextViewTextContent();
                    if (birthday == null || TextUtils.isEmpty(birthday.trim())) {
                        age = "30";
                    } else {
                        int ageI = 30;
                        try {
                            ageI = DateUtils.getAge(DateUtils.stringToDateTime(birthday));
                        } catch (Exception e) {
                        }
                        age = String.valueOf(ageI);
                    }
                }
                int iAge = Integer.parseInt(age);
                showNumberPickerDialog(TAG_AGE, iAge);
                break;
        }
    }

    private void showBirthdayPicker() {

        Date initDate = null;
        try {
            initDate = DateUtils.stringToDateTime(mBirthdayView.getTextViewTextContent());
        } catch (Exception e) {
            initDate = new Date();
        }
        if (initDate == null) {
            initDate = new Date();
            initDate.setYear(initDate.getYear() - 30);
        }

        Calendar c = Calendar.getInstance(Locale.getDefault());
        c.set((initDate.getYear() + 1900), initDate.getMonth(), initDate.getDate());

        PickerHelper.chooseBirthday(getContext(), c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                Calendar c = Calendar.getInstance(Locale.getDefault());
                c.set(year, month, dayOfMonth);
                Date d = c.getTime();
                if (TimeUtils.compareToday(d) > 0) {
                    UIHelper.makeToast(mContext, "出生日期不能晚于当天");
                    return;
                }

                String retBirth = DateUtils.dateTime2String(d, "yyyy-MM-dd");

                if (!TextUtils.isEmpty(retBirth)) {
                    mBirthdayView.setTextViewTextContent(retBirth);
                    mAgeView.setTextViewTextContent(
                            String.valueOf(TimeUtils.getAge(d)));
                    mIsConfirmed = 1;
                }
            }
        });
    }

    private void showNumberPickerDialog(int type, int defaultValue) {
        String title = null;
        String[] displayValues = null;
        switch (type) {
            case TAG_CAREER_CATEGORY:
                title = "职业类别";
                displayValues = getContext().getResources().getStringArray(R.array.customer_career_category);
                break;
            case TAG_EDUCATION_GRADING:
                title = "学历";
                displayValues = getContext().getResources().getStringArray(R.array.customer_education);
                break;
            case TAG_AGE:
                title = "年龄";
                int maxAge = 120;
                displayValues = new String[maxAge + 1];
                for (int i = 0; i < maxAge + 1; i++) {
                    displayValues[i] = String.valueOf(i);
                }
                break;
            case TAG_LEVEL://等级
                title = "等级";
                displayValues = getContext().getResources().getStringArray(R.array.customer_level);
                break;
        }
        NumberPickerDialog dialog = new NumberPickerDialog(getContext(), title, displayValues, defaultValue, type);
        dialog.setSelectedListener(this);
        dialog.show();
    }

    @Override
    public void onSelected(String content, int value, int type) {
        switch (type) {
            case TAG_CAREER_CATEGORY:
                if (!TextUtils.isEmpty(content)) {
                    mCareerView.setTextViewTextContent(content);
                }
                break;

            case TAG_LEVEL:
                if (!TextUtils.isEmpty(content)) {
                    mLevelView.setTextViewTextContent(content);
                }
                break;

            case TAG_EDUCATION_GRADING:
                if (!TextUtils.isEmpty(content)) {
                    mDegreeView.setTextViewTextContent(content);
                }
                break;
            case TAG_AGE:
                mAgeView.setTextViewTextContent(String.valueOf(value));
                mIsConfirmed = 0;
                Date date = new Date();
                date.setYear(date.getYear() - value);
                date.setMonth(0);
                date.setDate(1);

                mBirthdayView.setTextViewTextContent(DateUtils.dateTime2String(date, "yyyy-MM-dd"));
                mBirthdayView.setIsConfirmedUI(false);
                break;
        }
    }

    public static FragmentCustomerDetail newInstance(String mode, String uuid) {
        Bundle bundle = new Bundle();
        bundle.putString(CustomerConstant.CUSTOMER_DETAIL_MODE, mode);
        bundle.putString(CustomerConstant.CUSTOMER_UUID, uuid);
        FragmentCustomerDetail fragmentCustomerDetail = new FragmentCustomerDetail();
        fragmentCustomerDetail.setArguments(bundle);
        return fragmentCustomerDetail;
    }

    /**
     * 返回的数组由4个元素构成（暂定），其中：<br>
     * object[0]是此customer是否合法，数据类型：boolean <br>
     * object[1]是此customer不合法的检查结果，数据类型：String <br>
     * object[2]是此fragment中的customer对象，数据类型：Customer <br>
     * object[3]是此customer是否改变，数据类型：boolean <br>
     * object[4]是此fragment中的mAddress对象，数据类型：EntityCustomerAddress，先判断objec[5]是否时true(是否改变) <br>
     * object[5]是此mAddress是否改变，数据类型：boolean <br>
     * object[2]始终不为null <br>
     * 如果是新建状态，可以从object[2]的boolean判断是否有新的内容，true为新增了新的内容，false为没有新增内容 <br>
     * 如果是编辑状态，可以从object[2]的boolean判断是否有新的改变 <br>
     *
     * @return
     */
    public Object[] onCancel() {
        return getUltimateCustomerAndState();
    }

    /**
     * 当前暂时只返回前三个
     * <p>
     * 返回的数组由4个元素构成（暂定），其中：<br>
     * object[0]是此customer是否合法，数据类型：boolean <br>
     * object[1]是此customer不合法的检查结果，数据类型：String <br>
     * object[2]是此fragment中的customer对象，数据类型：Customer <br>
     * object[3]是此customer是否改变，数据类型：boolean <br>
     * object[4]是此fragment中的mAddress对象，数据类型：EntityCustomerAddress，先判断object[5]是否时true(是否改变) <br>
     * object[5]是此mAddress是否改变，数据类型：boolean <br>
     * object[6]是此fragment中的mPhones对象，数据类型：ACustomerInfoItemContent <br>
     * object[7]是此mPhones中各条数据是否改变的状态，暂时未使用 <br>
     * object[2]始终不为null <br>
     * 如果是新建状态，可以从object[2]的boolean判断是否有新的内容，true为新增了新的内容，false为没有新增内容 <br>
     * 如果是编辑状态，可以从object[2]的boolean判断是否有新的改变 <br>
     *
     * @return
     */
    public Object[] onFinish() {
        return getUltimateCustomerAndState();
    }

    private Object[] getUltimateCustomerAndState() {

        Object[] ultimateCustomerAndChangeState = new Object[8];

        if (mCustomerDetail == null) {
            mCustomerDetail = new CustomerDetail();
        }
        fetchContentIntoCustomer(mCustomerDetail);

        checkIfContentLegal(mCustomerDetail, ultimateCustomerAndChangeState);
        ultimateCustomerAndChangeState[2] = mCustomerDetail;
        ultimateCustomerAndChangeState[3] = isStringEqual(mOldPortraitPath, mNewPortraitPath);
        return ultimateCustomerAndChangeState;
    }

    private boolean isStringEqual(String oldS, String newS) {
        if (oldS == null) {
            return newS == null;
        }
        return oldS.equals(newS);
    }

    private void fetchContentIntoCustomer(CustomerDetail customerDetail) {

        customerDetail.setPortraitPath(mNewPortraitPath);
        //名字
        if (checkSetContentCondition(customerDetail.getName(), mNameView.getEditTextText())) {
            customerDetail.setName(mNameView.getEditTextText());
        }
        //是否为准确生日
        if (checkSetContentCondition(customerDetail.getIsConfirm(), mIsConfirmed)) {
            customerDetail.setIsConfirm(mIsConfirmed);
        }
        //学历
        if (checkSetContentCondition(customerDetail.getEducationGrading(), mDegreeView.getTextViewTextContent())) {
            customerDetail.setEducationGrading(CustomerConstant.EducationGrade.getEduInt(mDegreeView.getTextViewTextContent()));
        }
        //等级 A~E
        if (checkSetContentCondition(customerDetail.getLevel(), mLevelView.getTextViewTextContent())) {
            customerDetail.setLevel(mLevelView.getTextViewTextContent());
        }
        //生日 timeStamp
        if (!TextUtils.isEmpty(mBirthdayView.getTextViewTextContent())) {
            customerDetail.setBirthday(DateUtils.convertTimestampFromMilliToSecond(
                    DateUtils.stringToDateTime(mBirthdayView.getTextViewTextContent()).getTime()));
        }

        customerDetail.setSex((mSexRadios.getSelectedIndex() + 1) % 2);//当index是1时，sex为女
        customerDetail.setMarriage(mMarriageRadios.getSelectedIndex());

        customerDetail.setCareerCategory(CustomerConstant.CareerCategory.getCareerInt(mCareerView.getTextViewTextContent()));

        //sort key string
        if (!TextUtils.isEmpty(customerDetail.getName())) {
            String sortKeyString = PinyinUtil.generateDisplayStringSingle(customerDetail.getName());
            String sortKeyChar = String.valueOf(PinyinUtil.getSortKeyChar(sortKeyString));
            customerDetail.setNamePrefix(sortKeyChar);
        }

        setCustomerContact(customerDetail, CustomerConstant.CustomerContact.TYPE_PHONE, mPhoneView.getEditTextText());
        setCustomerContact(customerDetail, CustomerConstant.CustomerContact.TYPE_EMAIL, mEmailView.getEditTextText());
        //地址
        setCustomerAddress(customerDetail, mAddressView.getEditTextText());
        //身份证
        if (checkSetContentCondition(customerDetail.getIdCard(), mCreditcardView.getEditTextText())) {
            customerDetail.setIdCard(mCreditcardView.getEditTextText());
        }
        //添加默认的relationFlag 1
        setRelationFlag(customerDetail);
    }

    private void setRelationFlag(CustomerDetail customerDetail) {
        if (customerDetail == null) {
            return;
        }
        customerDetail.setRelationFlag(1);
    }

    private boolean checkSetContentCondition(String old, String now) {
        if (!(TextUtils.isEmpty(old) && TextUtils.isEmpty(now))) {
            if (now != null && !now.equals(old)) {
                return true;
            }
        }
        return false;
    }

    private boolean checkSetContentCondition(List<ACustomerInfoItemContent> phones, String now) {

        if (phones == null || phones.size() == 0) {
            return !TextUtils.isEmpty(now);
        }
        return !(phones.get(0) == null && TextUtils.isEmpty(now));
    }

    private boolean checkSetContentCondition(Object old, String now) {
        return !(old == null && TextUtils.isEmpty(now));
    }

    //mIsConfirmed
    //不相同的话，返回true
    //0,1
    private boolean checkSetContentCondition(Integer old, Integer now) {
        if (old == null) {
            if (now != null) {
                if (now == 0) {
                    return false;
                }
                return true;
            } else {
                return false;
            }
        } else {
            if (now == null) {
                if (old == 0) {
                    return false;
                }
                return true;
            } else {
                return old != now;
            }
        }
    }

    //检查输入内容是否合法
    private void checkIfContentLegal(CustomerDetail customerDetail, Object[] outInfo) {
        outInfo[0] = true;
        StringBuilder sbMessage = new StringBuilder();

        //检查姓名
        if (TextUtils.isEmpty(customerDetail.getName())) {
            outInfo[0] = false;
            sbMessage.append("请输入姓名");
        }

        //检查电话
        String phone = getCustomerContact(customerDetail, CustomerConstant.CustomerContact.TYPE_PHONE);
        if (!TextUtils.isEmpty(phone)) {
            String phoneCvalue = phone.replace(" ", "");
            if (!DataValidation.checkMobile(phoneCvalue) && !DataValidation.checkPhone(phoneCvalue)) {
                outInfo[0] = false;
                if (sbMessage.length() > 0) {
                    sbMessage.append(COMMA);
                }
                sbMessage.append("电话号码格式有误");
            }
        }

        //检查邮件
        String email = getCustomerContact(customerDetail, CustomerConstant.CustomerContact.TYPE_EMAIL);
        if (!TextUtils.isEmpty(email)) {
            if (!DataValidation.checkEmail(email)) {
                outInfo[0] = false;
                if (sbMessage.length() > 0) {
                    sbMessage.append(COMMA);
                }
                sbMessage.append("邮箱地址格式有误");
            }
        }
        outInfo[1] = sbMessage.toString();
    }

    /**
     * 选择照片
     */
    private PhotoCaptureUtil mPhotoCaptureUtil;

    private void toSelectPhoto(ImageView avatarView) {

        String tmpPath = EbtUtils.getCompletePortraitPath();//指定存放路径
        mPhotoCaptureUtil = new PhotoCaptureUtil(getContext());
        mPhotoCaptureUtil.setFrom(true);
        mPhotoCaptureUtil.setOnPhotoCaptureListener(new PhotoCaptureUtil.OnPhotoCaptureListener() {
            @Override
            public void onPhotoCaptured(final String path) {
                if (TextUtils.isEmpty(path) || !(new File(path).exists())) {
                    return;
                }
                if (mCustomerDetail == null) {
                    mCustomerDetail = new CustomerDetail();
                }

                mCustomerDetail.setPortraitPath(path);
                //头像
                CustomerUtil.setAvatarByUrlAndSex(getContext(), mAvatarView, mCustomerDetail.getPortraitPath(), mCustomerDetail.getSex());
                mNewPortraitPath = mCustomerDetail.getPortraitPath();
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        EbtMediaSannerClient client = new EbtMediaSannerClient(new File(path));
                        MediaScannerConnection mediaScanConn = new MediaScannerConnection(mContext, client);
                        client.setMediaScannerConnection(mediaScanConn);
                        mediaScanConn.connect();
                    }
                });
                t.start();
            }
        });
        String[] messages = new String[]{"相册", "拍照"};
        new MDEBTDialog.Builder(this.getActivity())
                .setMessages(messages)
                .setTitle("更改头像")
                .setNegativeButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setPositiveButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                })
                .setOnItemClickListener(new MDEBTDialog.OnItemClickListener() {
                    @Override
                    public void onItemClicked(int index) {
                        if (index == 0) {
                            mPhotoCaptureUtil.startActivity(PhotoCaptureUtil.FROM_ALBUM,
                                    ConfigData.PORTRAIT_WIDTH, ConfigData.PORTRAIT_HEIGHT, tmpPath);
                            TCAgent.onEvent(getContext(), "change_avatar", "from_album");
                        } else if (index == 1) {
                            mPhotoCaptureUtil.startActivity(PhotoCaptureUtil.FROM_CAMERA,
                                    ConfigData.PORTRAIT_WIDTH, ConfigData.PORTRAIT_HEIGHT, tmpPath);
                            TCAgent.onEvent(getContext(), "change_avatar", "from_camera");
                        }
                    }
                })
                .setShowPositiveButton(false)
                .create()
                .show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Customer event) {
        initValues();
    }

}